package com.mh.common;

import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Date:2025/2/28
 * author:zmh
 * description: 用户管理器
 **/

@Component
public class ChatSessionManager {
    // 存储用户openID，对话内容
    private static final Map<String, List<Message>> SESSIONS = new ConcurrentHashMap<>();
    // 初始化提示词
    private String systemPrompt;

    // 从文件加载系统提示（应用启动时执行）
    @PostConstruct
    public void init() throws IOException {
        systemPrompt = readMdFile(); // 修改为实际路径
    }

    // 创建新会话
    public Boolean createSession(String openId) {
        List<Message> newSession = new ArrayList<>();
        newSession.add(Message.builder()
                .role(Role.SYSTEM.getValue())
                .content(systemPrompt)
                .build());

        // 原子性操作：仅当openId不存在时插入新会话
        List<Message> existingSession = SESSIONS.putIfAbsent(openId, newSession);

        if (existingSession == null) {
            System.out.println("======> 创建新会话成功，OpenID: " + openId + " <=======");
        } else {
            System.out.println("======> 会话已存在，OpenID: " + openId + " <=======");
        }

        return true;
    }

    // 获取会话消息
    public List<Message> getMessages(String openId) {
        return SESSIONS.get(openId);
    }

    // 清理过期会话（可选）
    public void cleanExpiredSessions() {
        // 实现会话清理逻辑
    }

    // 读取md文档获取初始化提示词（让AI知道自己的职责）
    public String readMdFile() throws IOException {
        System.out.println("======> 读取到系统提示词 <=======");
        ClassPathResource resource = new ClassPathResource("static/system_prompt.md");
        byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
        return new String(bytes, StandardCharsets.UTF_8);
    }

}
